package com.m3958.firstgwt.server.utils;

import java.util.Calendar;

import com.google.common.base.CharMatcher;

public class Ymd{
	
	private Calendar c;
	
	public Calendar getC() {
		return c;
	}

	public void setC(Calendar c) {
		this.c = c;
	}

	public Ymd(Calendar c){
		this.c = c;
	}
	
	public Ymd(String dateStr){
		parseDateStr(dateStr);
	}
	
	private void parseDateStr(String dateStr){
		String theDigits = CharMatcher.DIGIT.retainFrom(dateStr);
		int l = theDigits.length();
		int year=-1,month=-1,date=-1;
		if(l == 4){
			year = Integer.parseInt(theDigits);
		}else if(l == 6){
			year = Integer.parseInt(theDigits.substring(0, 4));
			month = Integer.parseInt(theDigits.substring(4));
		}else if(l == 8){
			year = Integer.parseInt(theDigits.substring(0, 4));
			month = Integer.parseInt(theDigits.substring(4,6));
			date = Integer.parseInt(theDigits.substring(6));
		}else{
			;
		}
		this.c = Calendar.getInstance();
		if(year != -1)c.set(Calendar.YEAR,year);
		if(month != -1)c.set(Calendar.MONTH,month);
		if(date != -1)c.set(Calendar.DAY_OF_MONTH,date);
	}
	
	public int year(){
		return c.get(Calendar.YEAR);
	}
	
	public int month(){
		return c.get(Calendar.MONTH);
	}

	public int date(){
		return c.get(Calendar.DAY_OF_MONTH);
	}
	
	public Ymd ymd(String offset){
		Calendar nc = (Calendar) this.getC().clone();
		String num = CharMatcher.DIGIT.retainFrom(offset);
		String addType = CharMatcher.anyOf("YyMmDd").removeFrom(offset).toLowerCase();
		int addNum = Integer.valueOf(num);
		if(offset.indexOf('-') != -1){
			addNum = 0 - addNum;
		}
		if("y".equals(addType)){
			c.add(Calendar.YEAR, addNum);
		}else if("m".equals(addType)){
			c.add(Calendar.MONTH, addNum);
		}else if("d".equals(addType)){
			c.add(Calendar.DAY_OF_MONTH, addNum);
		}
		return new Ymd(nc);
	}
}